import Vue from 'vue';
import Vuex from 'vuex';
import { SET_SLIDERS, CREATE_WEBSOCKET, SET_MESSAGE } from './action.types';
import { getSlider } from '../api/public.api';
import WS from '@/utils/websocket';

Vue.use(Vuex);

interface Store {
  actions: Record<string, any>;
  getters: Record<string, any>;
  mutations: Record<string, any>;
  namespaced: boolean;
}
interface Modules {
  [propName: string]: Store;
}

const modules: Modules = {};
const files = require.context('./modules', false, /\.store\.ts$/);


files.keys().forEach((key) => {
  const store = files(key).default;
  const moduleName: string = key.replace(/\.\//, '').replace(/\.store\.ts$/, '');
  modules[moduleName] = store;
});


export default new Vuex.Store({
  state: {
    sliders: [],
    ws: null,
    message: '',
  },
  mutations: {
    [SET_SLIDERS](state, sliders){
      state.sliders = sliders;
    },
    [CREATE_WEBSOCKET](state, ws){
      state.ws = ws;
    },
    [SET_MESSAGE](state, message){
      state.message = message;
    },
  },
  actions: {
    async [SET_SLIDERS]({ commit }) {
      const { data } = await getSlider();
      commit(SET_SLIDERS, data);
    },
    async [CREATE_WEBSOCKET]({ commit }) {
      const ws = new WS();
      ws.create();
      commit(CREATE_WEBSOCKET, ws);
    },
  },
  modules,
});
